package com.mcms.service.dw;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ralasafe.user.User;

import com.mcms.service.common.DealResult;
import com.mcms.util.CalendarUtil;
import com.mcms.util.DBHelper;
import com.mcms.util.McmsApiConfig;
import com.mcms.web.vo.DWZResult;

/**
 * 图片上传类
 * 1.将图片上传至运行时目录下；同时将图片上传至备份文件目录下(配置文件中进行配置)
 * 2.将图片的路径信息及上传操作信息录入到数据库表中(MCMS_PICTURE_INFO)
 * @author leef
 */
public class ImgUploadService {

	public static void execute(HttpServletRequest request){
		
		boolean isSuc = true;// 操作结果的状态
		ImgUploadService imgUploadService = new ImgUploadService();
		
		//图片上传
		try {
			isSuc = imgUploadService.uploadImg(request);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//处理结果
		request.setAttribute("tabId", "page");
		DealResult.execute(request, isSuc);
	}
	
	/**
	 * 保存上传图片的信息至数据库表中
	 * @param request
	 * @param customId 当前图片所属客户的ID
	 * @return
	 */
	public boolean addImgInfo(HttpServletRequest request,String customId){
		
		boolean isSuc=true;
		
		// 获取图片信息入库的sql语句
		StringBuffer sqlSB = new StringBuffer();
		StringBuffer sqlConditon = new StringBuffer();
		String sqlStr = McmsApiConfig.get("sql_addCustom_dw_upload");
		if(sqlStr!=null && sqlStr.trim().length()>0){
			sqlSB.append(sqlStr.substring(0, sqlStr.indexOf("(")+1));
		}
		
		//获取参数
		String id = UUID.randomUUID().toString();
		List paramsList = new ArrayList();
		
		if(id!=null && id.trim().length()>0){
			sqlSB.append("id,");
			sqlConditon.append("(?,");
			paramsList.add(id);//id
		}
		
		if(customId!=null && customId.trim().length()>0){
			sqlSB.append("CUSTOM_ID,");
			sqlConditon.append("?,");
			paramsList.add(customId);//custom_id
		}

		String doctorId = getDoctorId(customId);//获取预约就诊号：渠道部门没能为客户进行预约就诊时，此可能为空
		if(doctorId!=null && doctorId.trim().length()>0){
			sqlSB.append("DOCTOR_ID,");
			sqlConditon.append("?,");
			paramsList.add(doctorId);//预约就诊号
		}
		
		String deptCode = request.getParameter("deptCode");//上传部门
		if(deptCode!=null && deptCode.trim().length()>0){
			sqlSB.append("UPLOAD_DEPT_ID,");
			sqlConditon.append("?,");
			paramsList.add(deptCode);//上传部门
		}
		
		String url = (String)request.getAttribute("imgUrl");// 照片放置路径及文件名称
		if(url!=null && url.trim().length()>0){
			sqlSB.append("URL,");
			sqlConditon.append("?,");
			paramsList.add(url);//
		}
		
		Map mcmsSession = (Map)request.getSession().getAttribute("mcmsSession");
		User user = (User)mcmsSession.get("mcmsUser");
		String userName = user.getId().toString();
		
//		String userName = request.getParameter("userName");//图片上传人
		if(userName!=null && userName.trim().length()>0){
			sqlSB.append("UPLOAD_ID,");
			sqlConditon.append("?,");
			paramsList.add(userName);//
		}
		
		sqlSB.append("UPLOAD_TIME)");
		sqlConditon.append("?)");
		paramsList.add(CalendarUtil.getCurrentDateTime());//upload_time 上传时间

		
		sqlStr = sqlSB.toString()+"values "+sqlConditon.toString();
		
		try {
			DBHelper dbh = DBHelper.getInstance();
			int result = dbh.execute(sqlStr,paramsList);
			if(result!=1){
				isSuc = false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return isSuc;
		
	}
	
	/**
	 * 文件上传
	 * @param request
	 * @return 是否上传成功 true:成功;false:失败;
	 * @throws ServletException
	 * @throws IOException
	 */
	public boolean uploadImg(HttpServletRequest request)
		throws ServletException, IOException {
		boolean isSuc=true;
		
		//	设定请求字符集,防止中文文件名乱码
	    request.setCharacterEncoding("UTF-8");

		//  错误或异常提示信息
		String errorMsg="";
		
		// 生成文件保存路径和本系统中的规范文件命名
//		String pathBak = "c:" + File.separator + "mcms_photo/";//上传文件保存的路径：备份路径-在工程之外，避免部署工程时导致图片丢失
		String pathBak = McmsApiConfig.get("pathBak");// 图片备份路径：此为外置目录
		String pathMiddle = initMiddlePath();
//		String custId = "11111111112222222222eeeeeeeeee55";
		String custId = request.getParameter("customId");
		String strFileName = null;
		
		//  判断form是否是multpart/form-data
		if(FileUpload.isMultipartContent(request)){
			
			 DiskFileItemFactory factory = new DiskFileItemFactory();
			 
			 // 设置上传工厂的限制
			 factory.setSizeThreshold(1024 * 1024 * 20);
			 
			 //new File(request.getRealPath("/")可以具体执行路径
			 factory.setRepository(new File(pathBak));
			 
			 // 创建一个上传文件的ServletFileUpload对象
			 ServletFileUpload upload = new ServletFileUpload(factory);
			 
			 // 设置最大的上传限制，-1表示无限制
			 upload.setSizeMax(1024 * 1024 * 20);
			 
			 // 处理HTTP请求，items是所有的表单项
			 try {
				List<FileItem> items = upload.parseRequest(request);
				if(null==items){
					errorMsg = "未上传文件，请选择...";
					isSuc = false;
				}else{
					
					for(FileItem fi : items){
						//判断提交表单元素，是否是上传组件(type=file)
						if(fi.isFormField()){
							errorMsg = "上传的不是文件类型";
						}else{
							// 取得文件类型
							String fileName = fi.getName();
							if(fileName!=null && !"".equals(fileName)&&fileName.length()>0)
							{
								//	strFileName = fileName.substring(fileName.lastIndexOf("\\")==-1?0:fileName.lastIndexOf("\\"),fileName.length());//获取原始上传文件的名称
								
								// 初始本系统中要求格式的文件名称
								strFileName = initFileName(custId,fileName);
								
								// 系统外备份路径(外置目录)：无路径则建立
								File pathFile = new File(pathBak + pathMiddle );
								if (!pathFile.exists())
									pathFile.mkdirs();
								
								//	系统所在路径(内部目录)：无路径则建立
								String basePath = (String)request.getAttribute("basePath");// 工程所在真实路径
								pathFile = new File(basePath + pathMiddle );
								if (!pathFile.exists())
									pathFile.mkdirs();
								
								// 指定两个路径输出流
								FileOutputStream fos = new FileOutputStream(pathBak + pathMiddle + strFileName);// 存入系统外备份路径
								FileOutputStream fosLocal = new FileOutputStream(basePath + pathMiddle + strFileName);// 存入本系统中路径
								request.setAttribute("imgUrl", pathMiddle + strFileName);// 入库用：文件的相对路径
								
								// 执行上传
								if (fi.isInMemory()) {
									fos.write(fi.get());
									fosLocal.write(fi.get());
								} else {
									BufferedReader is = new BufferedReader(
											new InputStreamReader(fi.getInputStream()));
									String str = null;
									while ((str += is.readLine()) != null) {
										byte[] buffer = str.getBytes("ISO-8859-1");
										fos.write(buffer);
										fosLocal.write(buffer);
									}
									is.close();
								}
								fos.close();
								fosLocal.close();
							}
							
							// 保存上传文件信息至数据库中
							ImgUploadService imgUploadService = new ImgUploadService();
							isSuc = imgUploadService.addImgInfo(request,custId);
						}
					}
					
					errorMsg="文件上传成功";
				}
			} catch (FileUploadException e) {
				errorMsg = "文件上传发生错误"+e.getMessage();
				e.printStackTrace();
				isSuc = false;
			}

		}else{
			 errorMsg = "提交的表单属性设置不正确，不是上传文件的表单";
			 isSuc = false;
		}
		
		// 组装返回结果信息
		request.setAttribute("message", errorMsg);
		return isSuc;
	}
	
	/**
	 * 根据客户ID获取
	 * @param customId 客户ID
	 * @return
	 */
	public String getDoctorId(String customId){
		String str = "";
		
		String sqlStr = "select t.id from mcms_custom_inquiry_info t where t.custom_subscribe_id = '"+customId+"'";
		
		try {
			DBHelper dbh = DBHelper.getInstance();
			List list = dbh.query(sqlStr);
			if(list==null || list.size()==0){
				return "";
			}
			str = list.get(0).toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return str;
	}
	
	/**
	 * 初始本次照片上传后放置的中间路径
	 * 格式：/upload/photo/年/月/日/
	 * @return
	 */
	public String initMiddlePath(){
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
		java.util.Date date=new java.util.Date();  
		String str=sdf.format(date);  
		System.out.println(str);
        String[] strs = str.split("\\-");
		System.out.println(strs[0]+" "+strs[1]+" "+strs[2]);
		
//		String basePath = getServletContext().getRealPath("/");// 当前系统的真实路径
		StringBuilder filePath = new StringBuilder();
		filePath.append("upload").append(File.separator);
		filePath.append("photo").append(File.separator);
		filePath.append(strs[0]).append(File.separator);
		filePath.append(strs[1]).append(File.separator);
		filePath.append(strs[2]).append(File.separator);
		
		
		return filePath.toString();
	}
	
	/**
	 * 初始本系统格式的文件名称
	 * 格式：custId_yyyy_MM_dd_HH_mm_ss.jpg
	 * 其中类型名称与原文件类型相同
	 * @param custId
	 * @param fileTrueName
	 * @return
	 */
	public String initFileName(String custId, String fileTrueName){
		
		// 初始文件类型：原文件类型
		String fileName = fileTrueName.substring(fileTrueName.lastIndexOf("\\")==-1?0:fileTrueName.lastIndexOf("\\"),fileTrueName.length());//获取原始上传文件的名称
		String fileType = "";
		if(fileName.indexOf(".")!=-1){
			fileType = fileName.substring(fileName.indexOf("."));	
		}
		
		// 文件类型时间戳组成部分：custId_yyyy_MM_dd_HH_mm_ss.jpg
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy_MM_dd_HH_mm_SS"); 
		java.util.Date date=new java.util.Date();  
		String str=sdf.format(date);  
		System.out.println(str);
		
		return custId+"_"+str+fileType;
	}
	
//	public void dealResult(HttpServletRequest request,boolean isSuc){
//		DWZResult dwzResult = new DWZResult();//"message":"操作成功", "navTabId":"navNewsLi", "forwardUrl":"", "callbackType":"closeCurrent"}
//		dwzResult.setNavTabId("page_dw2");
////		dwzResult.setRel("page_sc1"); 
//		dwzResult.setMessage("操作成功");  
//		dwzResult.setStatusCode("200");  
////		dwzResult.setCallbackType("closeCurrent");  
////		dwzResult.setForwardUrl("customList.html?userName=aaa&deptCode=sc&actionType=listCustom");
//		
//		request.setAttribute("dwzResult", dwzResult);
//	}
}
